<template>
    <div class="edu-page-warp">
        <div style="background:#fff;">
            <div class="base-sub-title">{{ studentCultureRel.major }}{{ $t("culturePlan.culturePlan") }}</div>
            <!--分类与课程统计-->
            <div style="width:100%;overflow:auto;">
                <table class="personal">
                    <thead>
                        <tr>
                            <th :colspan="tableDynamicColNum" style="min-width:200px">{{ $t("culturePlan.courseCategory") }}</th>
                            <th style="min-width:100px">{{ $t("culturePlan.courseCode") }}</th>
                            <th style="min-width:200px">{{ $t("culturePlan.courseName") }}</th>
                            <th style="min-width:100px">{{ $t("culturePlan.studyScore") }}</th>
                            <th style="min-width:100px">{{ $t("culturePlan.studyTime") }}</th>
                            <th style="min-width:150px">{{ $t("course.term") }}</th>
                            <th style="min-width:200px">{{ $t("label.openClassCollege") }}</th>
                            <th style="min-width:100px">{{ $t("culturePlan.obligatory") }}</th>
                            <th style="min-width:100px">{{ $t("culturePlan.remark") }}</th>
                            <th style="min-width:100px">{{ $t("culturePlan.selectCourse") }}</th>
                            <th style="min-width:100px">{{ $t("culturePlan.achievement") }}</th>
                            <th v-if="prev" style="min-width:100px">{{ $t("culturePlan.finishStatus") }}</th>
                            <th v-if="!prev" style="min-width:100px">{{ $t("message.operating") }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(c,_index) in courses" :key="_index">
                            <template v-for="col in c.label.labelMap">
                                <td
                                    v-if="col.rowspan!=0"
                                    :rowspan="col.rowspan"
                                    :colspan="col.colspan"
                                    :key="col.id"
                                >
                                    {{ col.name }}
                                    <!-- 测试单元跨数量{{col.name}},{{col.rowspan}},{{col.colspan}}-->
                                </td>
                            </template>
                            <!--数据列-->
                            <td v-if="c.type=='row'" class="nowrap">
                                <div class="nowrap" style="width:100px">
                                    <el-tooltip :content="c.code" placement="bottom" effect="light">
                                        <span>{{ c.code }}</span>
                                    </el-tooltip>
                                </div>
                            </td>
                            <td v-if="c.type=='row'" class="nowrap">
                                <div class="nowrap" style="width:200px">
                                    <el-tooltip :content="c.name" placement="bottom" effect="light">
                                        <a
                                            :class="{'new-record': c.changeStatus == 1,'edit-record': c.changeStatus == 2,'remove-record': c.changeStatus == 3 }"
                                            @click="showCourseDetail(c)"
                                        >{{ c.name }}</a>
                                    </el-tooltip>
                                </div>
                            </td>
                            <td v-if="c.type=='row'">{{ c.credits }}</td>
                            <td v-if="c.type=='row'">{{ c.period }}</td>
                            <td v-if="c.type=='row'">{{ c.term||'' }}</td>
                            <td v-if="c.type=='row'">{{ c.collegeI18n }}</td>
                            <td v-if="c.type=='row'">{{ c.compulsory | yesOrNo }}</td>
                            <td v-if="c.type=='row'">
                                <div class="nowrap" style="width:100px">
                                    <el-tooltip :content="c.remarks" placement="bottom" effect="light">
                                        <span>{{ c.remarks }}</span>
                                    </el-tooltip>
                                </div>
                            </td>
                            <td v-if="c.type=='row'"/>
                            <td v-if="c.type=='row'"/>
                            <!--空课程开始-->
                            <td v-if="c.type=='blank'" colspan="11" style="text-align:right">
                                <div style="margin-right:35px">
                                    <!-- <el-button
                                        type="text"
                                        size="mini"
                                        v-if="c.labelId == 999999"
                                        @click="showChooseCourseCrossFaultyDialog = true"
                                    >跨院系选课</el-button>
                                    <el-button
                                        type="text"
                                        size="mini"
                                        v-else
                                        @click="showAppendDialog(c)"
                                    >{{$t("culturePlan.addCourse")}}</el-button>-->
                                    <el-button
                                        v-if="999999 != c.labelId"
                                        type="text"
                                        size="mini"
                                        @click="showAppendDialog(c)"
                                    >{{ $t("culturePlan.addCourse") }}</el-button>
                                </div>
                            </td>
                            <!--空课程结束-->
                            <td v-if="prev"/>
                            <td v-if="c.type=='row'&&!prev" style="text-align:left">
                                <div v-if="c.labelId!=999999" style="margin-left:10px;">
                                    <el-button
                                        type="text"
                                        size="mini"
                                        @click="showDeleteDialog(c)"
                                    >{{ $t("culturePlan.cancelCourse") }}</el-button>
                                    <el-button
                                        v-if="c.isLast"
                                        type="text"
                                        size="mini"
                                        @click="showAppendDialog(c)"
                                    >{{ $t("culturePlan.add") }}</el-button>
                                </div>
                                <!-- <div>
                                    <el-button
                                        type="text"
                                        size="mini"
                                        v-if="c.isLast"
                                        @click="showChooseCourseCrossFaultyDialog = true"
                                    >跨院系选课</el-button>
                                </div>-->
                            </td>
                        </tr>
                        <tr>
                            <td :colspan="tableDynamicColNum+2">{{ $t("culturePlan.total") }}</td>
                            <td>{{ totalScore }}</td>
                            <td>{{ totalTime }}</td>
                            <td :colspan="tableStaticColNum-4"/>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div v-if="!prev" style="float:right;margin:10px 0">
            <el-button @click="back">{{ $t("message.cancel") }}</el-button>
            <el-button type="primary" @click="saveCourse">{{ $t("message.save") }}</el-button>
            <el-button type="primary" @click="submitCourse">{{ $t("message.submit") }}</el-button>
        </div>
        <!--添加课程对话框-->
        <el-dialog
            v-if="!prev"
            :title="$t('culturePlan.addCourse')"
            :visible.sync="showAddDialog"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="70%"
        >
            <div>
                <div class="edu-page-title">{{ $t("message.filterCondition") }}</div>
                <el-form label-position="left" label-width="70px">
                    <el-row :gutter="20">
                        <!-- <el-col :span="6">
                <el-form-item label="课程性质：">
                    <el-select v-model="queryForm.nature">
                        <el-option
                            v-for="item in options.nature"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-col>-->
                        <el-col :span="12">
                            <el-form-item :label="$t('label.openClassCollege')">
                                <el-select v-model="queryForm.college">
                                    <el-option
                                        v-for="item in options.college"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12" style="text-align:right">
                            <el-button @click="resetAddCourse">{{ $t("message.reset") }}</el-button>
                            <el-button
                                type="primary"
                                @click="filterAddCourse"
                            >{{ $t("message.filter") }}</el-button>
                        </el-col>
                    </el-row>
                </el-form>
                <div class="edu-page-title">
                    <el-row>
                        <el-col :span="8">{{ $t("culturePlan.courseList") }}</el-col>
                        <el-col :span="16" style="text-align:right">
                            <el-input
                                v-model="searchCourse"
                                :placeholder="$t('culturePlan.courseName')+'、'+$t('culturePlan.courseCode')"
                                style="width:240px"
                                @keyup.enter.native="searchAddCourse"
                            >
                                <i
                                    slot="suffix"
                                    class="el-icon-search"
                                    style="margin-top:10px;cursor:pointer"
                                    @click="searchAddCourse"
                                />
                            </el-input>
                            <el-button @click="clearAddCourse">{{ $t("culturePlan.clearChecked") }}</el-button>
                        </el-col>
                    </el-row>
                </div>
                <el-row :gutter="20">
                    <el-col>
                        <table class="personal" width="100%" style="margin:10px 0">
                            <thead>
                                <th style="width:130px">{{ $t('culturePlan.courseCode') }}</th>
                                <th>{{ $t('culturePlan.courseName') }}</th>
                                <th>{{ $t('culturePlan.studyScore') }}</th>
                                <th>{{ $t('culturePlan.studyTime') }}</th>
                                <th>{{ $t('culturePlan.semester') }}</th>
                                <th>{{ $t('culturePlan.obligatory') }}</th>
                                <th>{{ $t('culturePlan.remark') }}</th>
                            </thead>
                            <tbody>
                                <tr v-for="(c,_index) in filterLabelCourses" :key="_index">
                                    <td style="text-align:left">
                                        <div style="margin-left:10px">
                                            <el-checkbox
                                                v-if="c.disabled"
                                                v-model="c.checked"
                                                disabled
                                            />
                                            <el-checkbox v-if="!c.disabled" v-model="c.checked"/>
                                            <span style="margin-left:10px">{{ c.code }}</span>
                                        </div>
                                    </td>
                                    <td>{{ c.coursesName }}</td>
                                    <td>{{ c.credits }}</td>
                                    <td>{{ c.period }}</td>
                                    <td>{{ getSemester(c) }}</td>
                                    <td>{{ c.compulsory | yesOrNo }}</td>
                                    <td v-if="!c.courseGroupId">{{ c.parentRemark }}</td>
                                    <td
                                        v-if="c.courseGroupId&&c.rowspan"
                                        :rowspan="c.rowspan"
                                    >{{ c.parentRemark }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </el-col>
                </el-row>
                <div v-if="queryForm.isElective && queryForm.total_" class="edu-pagination">
                    <div class="float-right">
                        <el-pagination
                            :current-page="queryForm.pageNum_"
                            :page-sizes="[20,50,100,500,1000]"
                            :page-size="queryForm.pageSize_"
                            :total="queryForm.total_"
                            layout="total, sizes, prev, pager, next, jumper"
                            style="float: right;margin:0;"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                        />
                    </div>
                </div>
                <el-row v-if="rawLabelCourse.length>0">
                    <el-col>
                        <div style="text-align:right">
                            <el-button @click="cancelCourseSave">{{ $t("message.cancel") }}</el-button>
                            <el-button type="primary" @click="addCourseSave">{{ $t("message.save") }}</el-button>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </el-dialog>
        <el-dialog
            :title="$t('culturePlan.tipMessage')"
            :visible.sync="showRulesDialog"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="50%"
        >
            <div style="overflow:auto">
                <div style="color:red;line-height:30px">*{{ $t('culturePlan.condition') }}：</div>
                <div v-for="(c,index) in rules" :key="index" style="line-height:30px">
                    <div
                        v-if="c.type=='score'"
                    >{{ c.name }}，{{ $t('culturePlan.needScore') }}：{{ c.credit }}，{{ $t('culturePlan.currentScore') }}：{{ c.score }}</div>
                    <div
                        v-if="c.type=='num'"
                    >{{ c.name }}，{{ $t('culturePlan.maxCourseNum') }}：{{ c.maxNum }}，{{ $t('culturePlan.minCourseNum') }}：{{ c.minNum }}，{{ $t('culturePlan.currentCourseNum') }}：{{ c.num }}</div>
                    <div v-if="c.type=='foreign'">
                        <div>{{ $t('culturePlan.firstForeignMinCourse') }}:{{ c.rulesCode }}</div>
                        <div>{{ $t('culturePlan.courseLimit') }}:{{ c.maxNumber }}</div>
                        <div>{{ $t('culturePlan.selectedMinCourse') }}:{{ c.findCode }}</div>
                    </div>
                    <div v-if="c.type=='groupNum'">
                        <div>
                            {{ $t('culturePlan.courseCategory') }} {{ c.label }}：{{ c.groupRemark }} {{ c.parentRemark }}，
                            {{ $t('culturePlan.graduatePlan.maxnumCourses') }}：
                            <b
                                style="color:red"
                            >{{ c.maxNum }}</b>，
                            {{ $t('culturePlan.graduatePlan.minimumCourses') }}：
                            <b style="color:red">{{ c.minNum }}</b>，
                            {{ $t('culturePlan.graduatePlan.numberSelectedCourses') }}：
                            <b style="color:#009900">{{ c.actNum }}</b>
                        </div>
                    </div>
                    <div v-if="c.type=='groupCredits'">
                        <div>
                            {{ $t('culturePlan.courseCategory') }} {{ c.label }}：{{ c.groupRemark }} {{ c.parentRemark }}，
                            {{ $t('culturePlan.graduatePlan.requiredScore') }}
                            <b
                                style="color:red"
                            >{{ c.expression }} {{ c.minNum }}</b>，
                            {{ $t('culturePlan.graduatePlan.selectedCredits') }}：
                            <b style="color:#009900">{{ c.actNum }}</b>
                        </div>
                    </div>
                    <div v-if="c.type=='bigGroup'">
                        <div>
                            {{ c.label }} {{ c.groupRemark }}，{{ $t('culturePlan.courseTotal') }}：
                            <b
                                style="color:#993300"
                            >{{ c.totalNum }}</b>
                            ，{{ $t('culturePlan.requireNumber') }}：
                            <b
                                style="color:red"
                            >{{ c.planNum }}</b>
                            ，{{ $t('culturePlan.selectedNumber') }}：
                            <b
                                style="color:#009900"
                            >{{ c.actNum }}</b>
                        </div>
                    </div>
                    <div v-if="c.type=='categoryTotalScore'">
                        <div>
                            {{ $t('culturePlan.graduatePlan.courseTip') }}：
                            <b style="color:red">{{ c.planNum }}</b>，
                            {{ $t('culturePlan.graduatePlan.currentSelectedCredits') }}
                            <b
                                style="color:#009900"
                            >{{ c.actNum }}</b>
                        </div>
                    </div>
                </div>

                <div style="float:right">
                    <el-button type="primary" @click="closeRulesDialog">{{ $t("message.confirm") }}</el-button>
                </div>
            </div>
        </el-dialog>
        <el-dialog
            :title="$t('culturePlan.cultureSchemePreview')"
            :visible.sync="showCulturePrev"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="50%"
            class="prevDialog"
            append-to-body
        >
            <schemePreview :scheme="scheme" :template-id="cultureId" :data-type="2"/>
        </el-dialog>
        <el-dialog
            :title="$t('culturePlan.historyRecord')"
            :visible.sync="showHistoryDialog"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="30%"
            append-to-body
        >
            <div style="min-height:200px">
                <div v-for="(item,index) in history" :key="item.id" style="line-height:25px">
                    <span
                        v-if="item.actionType==1||item.actionType==2"
                    >{{ index+1 }}.{{ item.changeContent }}，{{ item.actionDate }}</span>
                    <span
                        v-if="item.actionType==3"
                        style="color:red"
                    >{{ index+1 }}.{{ item.changeContent }}，{{ item.actionDate }}</span>
                    <span
                        v-if="item.actionType==4"
                        style="color:green"
                    >{{ index+1 }}.{{ item.changeContent }}，{{ item.actionDate }}</span>
                </div>
            </div>
        </el-dialog>
        <courseDetail
            v-if="showCourseDialog"
            :couse-detail="couseDetail"
            :show-course-dialog="showCourseDialog"
            @closeCourseDialog="handlerCloseCourseDialog"
        />
        <ChooseCourseCrossFaulty
            :is-show="showChooseCourseCrossFaultyDialog"
            :student="studentCultureRel"
            @reload-plan="reloadPlan"
            @change-visible="showChooseCourseCrossFaultyDialog = false"
        />
    </div>
</template>
<script>
import { yesOrNo } from 'common/src/filters/commonFilter'
import {
    getCulturePlanByStudentId,
    getCultureCourseByParam,
    saveCulturePlan,
    updateCulturePlan,
    findStudentCultureRelById,
    updateStudentCultureRelStatus,
    culturePlanActionHistory
} from 'common/src/api/culture/culturePlan'
import scoreStatistics from './scoreStatistics'
import schemePreview from '../culturescheme/schemePreview'
import { mapActions } from 'vuex'
import { build, validate, PLAN_STATUS } from './culturePlan'
import { queryDic } from 'common/src/api/dictionary'
import { findFaculty } from 'common/src/api/faculty'
import UTILS from 'common/src/utils/utils'
import ChooseCourseCrossFaulty from './ChooseCourseCrossFaulty'
import courseDetail from 'common/src/views/culture/common/courseDetail'
export default {
    name: 'UndergraduatePlan',
    components: {
        scoreStatistics,
        schemePreview,
        ChooseCourseCrossFaulty,
        courseDetail
    },
    filters: {
        yesOrNo
    },
    props: {
        studentCultureRel: {
            default: null // 个人培养计划信息,避免重复查询
        },
        data: {
            default: null // 业务数据，包含培养计划、规则、培养方案数据
        },
        prev: {
            default: false
        },
        isPass: {
            default: 0
        },
        culturePlanListLength: {
            default: 0
        }
    },
    data() {
        return {
            showChooseCourseCrossFaultyDialog: false,
            uid: '',
            rawLabels: null, // 原生课程分类集合
            rawCourses: null, // 原生课程集合
            rawRules: null,
            foreigns: null, // 外国语关系
            courses: [], // 计划列表，(视图绑定的数据)
            tableDynamicColNum: 1, // 动态列数，为课程分类层级最大数
            tableStaticColNum: 11, // 表格静态列数
            totalScore: 0, // 合计学分
            totalTime: 0, // 合计学时
            showAddDialog: false, // 是否显示添加对话框
            showRulesDialog: false, // 是否显示规则对话框
            showCulturePrev: false, // 是否显示预览对话框
            showHistoryDialog: false, // 显示历史记录对话框

            deleteCourseIds: [], // 删除的课程Id集合
            rules: [],
            cultureId: '', // 培养方案id
            scheme: null, // 培养方案对象
            history: [],
            cultureCourseLabelRelationList: [], // 培养计划
            /** 添加课程相关属性**/
            searchCourse: null,
            rawLabelCourse: [], // 添加课程，课程分类下所有课程列表
            filterLabelCourses: [], // 添加课程，过滤后的课程列表
            categoryTotalScore: 0,
            statusPlan: '',
            isShowPlan: false,
            options: {
                kkxq: [],
                college: [],
                nature: []
            },
            queryForm: {
                nature: '',
                term: '',
                college: '',
                labelId: '',
                isElective: '',
                pageSize_: 20,
                pageNum_: 1,
                total_: 0
            },
            showCourseDialog: false,
            couseDetail: {}
        }
    },
    mounted() {
        this.init()
        this.statusPlan = this.$route.query.statusPlan
    },
    methods: {
        ...mapActions(['delTab']),
        reloadPlan() {
            this.showChooseCourseCrossFaultyDialog = false
            this.init()
        },
        init() {
            findFaculty().then(res => {
                const data = { 'X_YX': res.data }
                UTILS.fillSelect({ college: 'X_YX' }, data, this.options)
            })
            const data = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: ['X_KKXQ', 'X_KCXZ']
            }
            queryDic(data).then(res => {
                if (res.code == 200) {
                    UTILS.fillSelect(
                        { kkxq: 'X_KKXQ', nature: 'X_KCXZ' },
                        res.data,
                        this.options
                    )
                    this.getCourseInfo()
                }
            })
        },
        getCourseInfo() {
            if (this.studentCultureRel) {
                this.uid = this.studentCultureRel.studentId
                if (this.data) {
                    var hasPublicCourse = false
                    this.rawLabels = this.data.coursesLabelList
                    this.data.templateRuleList.forEach(r => {
                        const obj = this.rawLabels.find(
                            label => label.labelId == r.labelId
                        )
                        if (obj) {
                            r.pid = obj.parentId
                            r.name = obj.label
                        } else if (r.labelId == '999999') {
                            hasPublicCourse = true
                            r.pid = '999999'
                            r.name = this.$t('culturePlan.graduatePlan.crossDepartmentalCourses')
                        }
                    })
                    this.rawRules = this.data.templateRuleList.filter(
                        r => r.pid != null
                    )
                    // 移除重复课程分类
                    this.rawLabels = _.uniqWith(this.rawLabels, _.isEqual)
                    //   if (hasPublicCourse)
                    this.rawLabels.push({
                        label: this.$t('culturePlan.graduatePlan.crossDepartmentalCourses'),
                        labelId: '999999',
                        parentId: '0'
                    })
                    this.cultureCourseLabelRelationList = this.data.cultureCourseLabelRelationList
                    // 判断数据来源，是培养计划还是培养方案
                    this.rawCourses =
                        this.data.culturePlanList &&
                        this.data.culturePlanList.length > 0
                            ? this.data.culturePlanList
                            : _.cloneDeep(
                                this.data.cultureCourseLabelRelationList
                            )
                    this.foreigns = this.data.complationsContrastList
                    this.categoryTotalScore = this.data.cultureSchemeTotalScoreRule
                    this.buildViewData()
                }
            }
        },
        buildViewData() {
            const obj = build(this.rawLabels, this.rawCourses, !this.prev, false, true)
            // console.log(obj.courses)
            this.courses = obj.courses
            // changeStatus赋值
            if (this.courses && this.statusPlan != 3) {
                this.courses.forEach(d => {
                    d.changeStatus = 0
                })
            }
            this.tableDynamicColNum = obj.tableDynamicColNum
            this.totalScore = obj.totalScore
            this.totalTime = obj.totalTime
        },
        // 显示删除对话框提示
        showDeleteDialog(course) {
            this.$confirm(
                this.$t('culturePlan.confirmDeleteCourse'),
                this.$t('message.prompt'),
                {
                    confirmButtonText: this.$t('message.confirm'),
                    cancelButtonText: this.$t('message.cancel'),
                    type: 'warning'
                }
            )
                .then(() => {
                    this.confirmDelete(course)
                })
                .catch(e => {})
        },
        showAppendDialog(course) {
            this.resetAddCourse()
            const studentId = this.uid
            this.queryForm.labelId = course.label.labelId
            this.searchCourse = ''
            this.rawLabelCourse = []
            this.filterLabelCourses = []

            if (course.label.labelType === '1') {
                this.queryForm.isElective = this.isElective = '1'
                this.queryForm.pageSize_ = 20
                this.queryForm.pageNum_ = 1
                this.queryForm.total_ = 0
            } else {
                this.queryForm.pageSize_ = null
                this.queryForm.pageNum_ = null
                this.queryForm.total_ = null
            }
            this.getAddCourses(
                studentId,
                this.queryForm.labelId,
                this.queryForm.isElective,
                this.queryForm.pageNum_,
                this.queryForm.pageSize_,
                this.$route.query.templateId
            )
            this.showAddDialog = true
        },
        getAddCourses(
            studentId,
            labelId,
            isElective,
            pageNum_,
            pageSize_,
            templateId
        ) {
            // 绑定该分类下已经存在的课程
            const selectedCourses = this.courses.filter(
                c => c.labelId == this.queryForm.labelId
            )
            // 查询所有分类下的课程
            getCultureCourseByParam(
                studentId,
                labelId,
                null,
                null,
                null,
                isElective,
                pageNum_,
                pageSize_,
                templateId
            ).then(res => {
                let data = []
                if (res.code == 200) {
                    if (isElective) {
                        data = res.data.list || []
                        this.queryForm.total_ = res.data.total_ || 0
                        _.each(data, c => {
                            c.fromElectiveAdd = true
                        })
                    } else {
                        data = res.data
                    }
                    _.each(data, c => {
                        if (selectedCourses.some(c_ => c_.code == c.code)) {
                            c.disabled = true
                            c.checked = true
                        } else {
                            c.checked = false
                        }
                    })
                    this.rawLabelCourse = data
                    this.filterLabelCourses = _.cloneDeep(
                        this.calculateRowSpan(data)
                    )
                }
            })
        },

        handleSizeChange(val) {
            this.queryForm.pageSize_ = val
            this.getAddCourses(
                this.uid,
                this.queryForm.labelId,
                this.queryForm.isElective,
                this.queryForm.pageNum_,
                this.queryForm.pageSize_
            )
        },
        handleCurrentChange(val) {
            this.queryForm.pageNum_ = val
            this.getAddCourses(
                this.uid,
                this.queryForm.labelId,
                this.queryForm.isElective,
                this.queryForm.pageNum_,
                this.queryForm.pageSize_
            )
        },
        // 添加培养计划
        addCulturePlanHandle(status, msg) {
            const labelIds = []

            const data = []
            this.courses.forEach(c => {
                if (c.type == 'row' && labelIds.indexOf(c.labelId) == -1) {
                    labelIds.push(c.labelId)
                }
            })
            labelIds.forEach(id => {
                const courses = this.courses
                    .filter(
                        c =>
                            c.type == 'row' &&
                            c.labelId == id &&
                            !c.fromElectiveAdd
                    )
                    .map(c => c.id)
                const fromElectiveAddCourses = this.courses
                    .filter(
                        c =>
                            c.type == 'row' &&
                            c.labelId == id &&
                            c.fromElectiveAdd
                    )
                    .map(c => c.courseId)
                const obj = {
                    labelId: id,
                    coursesRelId: courses
                }
                if (fromElectiveAddCourses && fromElectiveAddCourses > 0) {
                    obj.courseIdList = fromElectiveAddCourses
                }
                data.push(obj)
            })
            if (data.length == 0) {
                this.$message({
                    type: 'error',
                    message: this.$t('culturePlan.undergraduatePlan.addCourse')
                })
                return
            }
            saveCulturePlan(
                data,
                this.uid,
                status,
                this.studentCultureRel.teacherId
            ).then(res => {
                if (res.code == 200) {
                    this.$message({
                        type: 'success',
                        message: msg
                    })
                    this.back()
                }
            })
        },
        // 更新培养计划
        updateCulturePlanHandle(status, msg) {
            const data = []
            // 添加行
            this.courses.forEach(c => {
                if (c.command == 'addRow') {
                    data.push({
                        operation: '1',
                        courseLabelRelationId: c.id
                    })
                }
            })
            // 删除行
            this.deleteCourseIds.forEach(c => {
                data.push({
                    operation: '2',
                    courseCode: c.code,
                    id: c.id
                })
            })
            if (data.length > 0) {
                updateCulturePlan(
                    data,
                    this.uid,
                    status,
                    this.studentCultureRel.teacherId
                ).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            type: 'success',
                            message: msg
                        })
                        this.back()
                    }
                })
            } else {
                if (status == PLAN_STATUS.checking) {
                    updateStudentCultureRelStatus(
                        this.uid,
                        PLAN_STATUS.checking,
                        this.studentCultureRel.teacherId
                    ).then(res => {
                        if (res.code == 200) {
                            this.$message({
                                type: 'success',
                                message: msg
                            })
                            this.back()
                        }
                    })
                } else {
                    this.back()
                }
            }
        },
        // 保存
        saveCourse() {
            if (this.studentCultureRel.statusPlan == PLAN_STATUS.none || PLAN_STATUS.pass && !this.culturePlanListLength) {
                this.addCulturePlanHandle(
                    PLAN_STATUS.draft,
                    this.$t('culturePlan.success')
                )
            } else {
                this.updateCulturePlanHandle(
                    PLAN_STATUS.draft,
                    this.$t('culturePlan.success')
                )
            }
        },
        // 提交
        submitCourse() {
            if (!this.studentCultureRel.teacherId) {
                this.$message({
                    type: 'warning',
                    message: this.$t('culturePlan.undergraduatePlan.cannotSubmit')
                })
                return
            }
            const result = validate(
                this.rawLabels,
                this.courses,
                this.rawRules,
                this.foreigns,
                this.cultureCourseLabelRelationList,
                this.categoryTotalScore
            )
            if (!result.success) {
                this.showRulesDialog = true
                this.rules = result.errors
                return
            }
            this.$confirm(
                this.$t('culturePlan.confirmSubmitPlan') +
                    "<br/><span style='color:red'>*" +
                    this.$t('culturePlan.checkNoCancel') +
                    '</span>',
                this.$t('message.prompt'),
                {
                    confirmButtonText: this.$t('message.confirm'),
                    cancelButtonText: this.$t('message.cancel'),
                    type: 'warning',
                    dangerouslyUseHTMLString: true
                }
            ).then(() => {
                if (this.studentCultureRel.statusPlan == PLAN_STATUS.none || PLAN_STATUS.pass && !this.culturePlanListLength) {
                    this.addCulturePlanHandle(
                        PLAN_STATUS.checking,
                        this.$t('culturePlan.success')
                    )
                } else {
                    this.updateCulturePlanHandle(
                        PLAN_STATUS.checking,
                        this.$t('culturePlan.success')
                    )
                }
            })
        },
        // 返回
        back() {
            this.isShowPlan = true
            this.$emit('showPlan', this.isShowPlan)
        },
        // 重置添加课程
        resetAddCourse() {
            this.queryForm.nature = ''
            this.queryForm.college = ''
            this.queryForm.term = ''
            this.searchCourse = ''
            this.queryForm.isElective = ''
            this.isElective = null
        },
        // 筛选添加课程
        filterAddCourse() {
            const selectedCourses = this.courses.filter(
                c => c.labelId == this.queryForm.labelId
            )

            this.getAddCourses(
                this.uid,
                this.queryForm.labelId,
                this.queryForm.isElective,
                this.queryForm.pageNum_,
                this.queryForm.pageSize_
            )
        },
        // 保存课程添加
        addCourseSave() {
            if (!this.showAddDialog) {
                return
            }
            this.showAddDialog = false
            const customed =
                this.studentCultureRel.statusPlan != 1
            // 获取可选且选中的复选框的课程
            const courses = this.filterLabelCourses.filter(
                c => !c.disabled && c.checked
            )
            if (courses && courses.length > 0) {
                courses.forEach(c => {
                    let isOldCourse = false
                    if (
                        customed &&
                        this.deleteCourseIds
                            .map(c_ => c_.courseLabelRelationId)
                            .includes(c.id)
                    ) {
                        _.remove(
                            this.deleteCourseIds,
                            c_ => c_.courseLabelRelationId == c.id
                        )
                        isOldCourse = true
                    }
                    const addRow = {
                        id: c.id,
                        courseId: c.courseId,
                        code: c.code,
                        name: c.coursesName,
                        nameEn: c.coursesNameEn,
                        credits: c.credits,
                        period: c.period, // 未确定的字段
                        term: c.term, // 未确定的字段
                        labelId: c.labelId,
                        fromElectiveAdd: c.fromElectiveAdd,
                        isElective: c.isElective,
                        courseGroupId: c.courseGroupId,
                        parentId: c.parentId,
                        groupRemark: c.groupRemark, // 未统一
                        parentRemark: c.parentRemark,
                        chooseNum: c.chooseNum,
                        totalNum: c.totalNum,
                        parentChooseNum: c.parentChooseNum,
                        parentTotalNum: c.parentTotalNum,
                        collegeI18n: c.collegeI18n || c.college, // 无数据
                        remark: c.remarks, // 无数据
                        compulsory: c.compulsory // 是否必修
                    }
                    if (customed && !isOldCourse) {
                        addRow.command = 'addRow'
                    }
                    this.rawCourses.push(addRow)
                })
                this.buildViewData()
            }
        },
        /**
         * 删除课程
         */
        confirmDelete(course) {
            _.remove(this.rawCourses, c => c.id == course.id)
            if (this.studentCultureRel.statusPlan != 1 && !course.command) {
                this.deleteCourseIds.push({
                    id: course.id,
                    code: course.code,
                    courseLabelRelationId: course.courseLabelRelationId
                }) // 仅保存旧课程Id，command==addRow为新课程
            }
            this.buildViewData()
        },
        // 取消课程添加
        cancelCourseSave() {
            this.showAddDialog = false
        },
        // 取消规则对话框
        closeRulesDialog() {
            this.showRulesDialog = false
        },
        // 获取季度文本值
        getQuarter(semesters) {
            if (semesters) {
                const quarters = semesters
                    .split(',')
                    .map(v => {
                        if (v == 1) {
                            return this.$t('culturePlan.spring')
                        } else if (v == 2) {
                            return this.$t('culturePlan.autumn')
                        } else if (v == 3) {
                            return this.$t('culturePlan.springautumn')
                        } else {
                            return null
                        }
                    })
                    .filter(s => s != null)
                return quarters && quarters.length > 0
                    ? quarters.join(',')
                    : ''
            } else {
                return ''
            }
        },
        searchAddCourse() {
            const courses = this.rawLabelCourse.filter(c => {
                return (
                    c.code.indexOf(this.searchCourse) > -1 ||
                    (c.coursesName &&
                        c.coursesName.indexOf(this.searchCourse) > -1) ||
                    (c.coursesNameEn &&
                        c.coursesNameEn.indexOf(this.searchCourse) > -1)
                )
            })
            this.filterLabelCourses = this.calculateRowSpan(
                _.cloneDeep(courses)
            )
        },
        clearAddCourse() {
            this.filterLabelCourses.forEach(c => {
                if (!c.disabled) {
                    c.checked = false
                }
            })
        },
        calculateRowSpan(courses) {
            const groupIds = []
            if (courses && courses.length > 0) {
                courses.forEach(c => {
                    if (
                        c.courseGroupId &&
                        !groupIds.includes(c.courseGroupId)
                    ) {
                        groupIds.push(c.courseGroupId)
                    }
                })
                const handleIds = []
                groupIds.forEach(groupId => {
                    courses.forEach(c => {
                        if (
                            c.courseGroupId == groupId &&
                            !handleIds.includes(c.courseGroupId)
                        ) {
                            handleIds.push(c.courseGroupId)
                            c.rowspan = courses.filter(
                                c_ => c_.courseGroupId == groupId
                            ).length
                        }
                    })
                })
            }

            return courses
        },
        getIsElectiveText(val) {
            if (val >= 0) {
                return val == 1 ? this.$t('culturePlan.graduatePlan.textFalse') : this.$t('culturePlan.graduatePlan.textTrue')
            } else {
                return ''
            }
        },
        getSemester(row) {
            for (let i = 1; i <= 16; i++) {
                if (row['semester' + i]) {
                    return i
                }
            }
        },
        showCourseDetail(c) {
            this.couseDetail = c
            this.showCourseDialog = true
        },
        handlerCloseCourseDialog() {
            this.showCourseDialog = false
        }
    }
}
</script>
<style lang="scss" scoped>
.base-title {
    border-bottom: 1px solid #cccccc;
    line-height: 30px;
    margin-bottom: 20px;
}
.base-sub-title {
    text-align: center;
    font-size: 20px;
    padding-bottom: 20px;
}
.personal {
    border-collapse: collapse;
    border: 1px solid #000000;
    td,
    th {
        text-align: center;
        line-height: 30px;
        border-collapse: collapse;
        border: 1px solid #a5a5a5;
        background: #fff;
        color: #606266;
    }
}
.nowrap {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}
.one-btn {
    width: 60px;
}
.two-btn {
    width: 130px;
}
</style>
